package com.weepal.pavement.mqtt.demo.config.dataSource;

import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.annotation.NacosConfigurationProperties;
import com.weepal.pavement.mqtt.demo.vo.DataSourceVo;
import com.zaxxer.hikari.HikariDataSource;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Data
@Component
@NacosConfigurationProperties(dataId = "dataSource", type = ConfigType.YAML, prefix = "datasource", autoRefreshed = true)
public class NacosDynamicsDataSources {
    private Map<String, DataSourceVo> ds;

    private ArrayList<String> sourceNames = new ArrayList<>(10);

    public String foo() {
        return ds.toString();
    }

    public Map<Object, Object> buildSource() {
        final String DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        ConcurrentHashMap<Object, Object> result = new ConcurrentHashMap<>();
        for (Map.Entry<String, DataSourceVo> entry : ds.entrySet()) {
            DataSourceVo vo = entry.getValue();
            HikariDataSource dataSource = new HikariDataSource();
            dataSource.setJdbcUrl(vo.getUrl());
            dataSource.setUsername(vo.getUserName());
            dataSource.setPassword(vo.getPassword());
            dataSource.setDriverClassName(DRIVER);
            result.put(entry.getKey(), dataSource);
            sourceNames.add(entry.getKey());
        }
        return result;
    }

    public ArrayList<String> getAllNames() {
        return sourceNames;
    }
}
